# -*- coding: utf-8 -*-
"""
Created on Wed Nov 14 23:35:09 2012

@author: Maxim
"""

import numpy as ny
from math import sin,cos,tan,degrees, radians

def load_airfoil_txt(path):
    """
    Reads in airfoil text file and returns Airfoil3D object
    
    Parameters
    ----------
    path : file path
        full path to the airfoil text file
    """
    af = Airfoil3D()
    af.read_txt(path)
    return af

class Airfoil3D():
    def __init__(self):
        self.createRadius = False
        self.R = 0.0
        self.Rcenter = ny.array([0.0,0.0,0.0])
        self.chord = 0.0
    
    def read_txt(self,path):
        afFile = open(path,'rt')
        self.name = afFile.readline()[:-1]
        self.coord = ny.array([0.,0])
        for line in afFile:
            if line.strip()!='':
                segLine = line.split()
                coord = [float(segLine[0]), float(segLine[1])]
                self.coord = ny.vstack([self.coord,coord])
        self.coord = self.coord[1:,:]
        self._separate_coordinates()
        afFile.close()
    
    def write_txt(self, filePath, tab=True):
        afFile = open(filePath,'wt')
        afFile.write((self.name + '\n'))
        if self.coord == []:
            self._join_coordinates()
        if tab:
            whiteSpace = '\t'
        else:
            whiteSpace = '    '
        for pt in self.coord:
            afFile.write('%.6f%s%.6f\n'%(pt[0], whiteSpace, pt[1]))
        afFile.close()
    def get_dist(self,pt1,pt2=[0.0,0.0]):
            return ((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)**0.5

    def _separate_coordinates(self):
        minDist = 1.0
        for i,pt in enumerate(self.coord):
            newDist = self.get_dist(pt)
            if newDist < minDist:
                minDist = newDist
                minIdx = i
        self.upOrig = ny.flipud(self.coord[:minIdx+1])
        self.loOrig = self.coord[minIdx:]
        self.upDim  = self.upOrig.shape[0]
        self.loDim  = self.loOrig.shape[0]
        
    def _join_coordinates(self):
        up = ny.flipud(self.upOrig[1:])
        self.coord = ny.vstack([up,self.loOrig])
        
    def set_le_radius(self,R,leCamberAngle):
        self.createRadius = True
        self.R = float(R)
        self.leCamberAngle = float(leCamberAngle)
        leAngle = radians(self.leCamberAngle)
        self.Rcenter = ny.array([self.R*cos(leAngle),self.R*sin(leAngle)])

    def set_chord(self,chord=1000):
        self.chord = float(chord)
        self.upScaled = self.upOrig*self.chord
        self.loScaled = self.loOrig*self.chord
        self.R  = self.R *self.chord
        self.Rcenter = self.Rcenter*self.chord
    
    def set_te_gap(self,teGap=0.0):
        self.teGap = float(teGap)
        gapUp = self.upScaled[-1,1]
        gapLo = -self.loScaled[-1,1]
        self.upScaled[:,1] += self.upOrig[:,0]*(self.teGap/2 - gapUp)
        self.loScaled[:,1] += self.loOrig[:,0]*(gapLo - self.teGap/2)

    def set_plane(self,plane):
        self.plane = plane
        self.up = ny.zeros([self.upDim,3])
        self.lo = ny.zeros([self.loDim,3])
        if plane == 'xy':
            self.up[:,0] = self.upScaled[:,0]
            self.up[:,1] = -self.upScaled[:,1]
            self.lo[:,0] = self.loScaled[:,0]
            self.lo[:,1] = -self.loScaled[:,1]
            self.Rcenter = ny.array([self.Rcenter[0], -self.Rcenter[1], 0.0])
        elif plane == 'xz':
            self.up[:,0] = self.upScaled[:,0]
            self.up[:,2] = self.upScaled[:,1]
            self.lo[:,0] = self.loScaled[:,0]
            self.lo[:,2] = self.loScaled[:,1]
            self.Rcenter = ny.array([self.Rcenter[0], 0.0, self.Rcenter[1]])


def run_test():
    path = 'naca2415.txt'
    af = Airfoil3D()
    af.read_txt(path)
    af.set_le_radius(1.1019*0.0225,0.91665425638528775)
    af.set_chord(1200)
    af.set_te_gap()
    af.set_plane('xz')
    
if __name__ == "__main__":
    run_test()